package com.example.foodsy.filter;

import com.example.foodsy.utils.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtils jwtUtils;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        // 从请求头中获取令牌（格式：Bearer <token>）
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final Integer userId;
        final String role;

        // 校验令牌格式
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // 提取令牌
        jwt = authHeader.substring(7);
        try {
            // 解析用户ID和角色
            userId = jwtUtils.extractUserId(jwt);
            role = jwtUtils.extractRole(jwt);

            // 如果令牌有效且未设置认证信息
            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                // 关键修复：将角色封装为权限对象（因已移除ROLE_前缀，直接使用role）
                List<GrantedAuthority> authorities = Collections.singletonList(
                        new SimpleGrantedAuthority(role) // 权限列表中添加ADMIN角色
                );
                // 构建认证令牌（角色需要以ROLE_为前缀，Spring Security规范）
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userId, // 存储用户ID
                        null,
                        authorities // 传入包含ADMIN角色的权限列表
                );
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                // 设置认证信息到上下文
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        } catch (Exception e) {
            // 令牌解析失败（过期或无效），不设置认证信息
            logger.error("无法解析JWT令牌");
        }

        // 继续执行过滤链
        filterChain.doFilter(request, response);
    }
}